package com.ecp.commons.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.ecp.commons.Environment;
import com.ecp.commons.file.DateBasedRenamePolicy;
import com.ecp.commons.file.HintTag;
import com.ecp.commons.file.MultipartRequest;

public class MultipartFilter extends AbstractExcludeUrlFilter {

	private static final long	serialVersionUID	= 1L;

	public MultipartFilter() {
		super();
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		if (!this.doInclude(servletRequest, servletResponse, filterChain)) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		if (this.doExclude(servletRequest, servletResponse, filterChain)) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		if (servletRequest.getContentType() != null
				&& servletRequest.getContentType().startsWith("multipart/form-data")) {
			HttpServletRequest httprequest = (HttpServletRequest) servletRequest;
			try {
				Environment env = Environment.getEnv();
				int maxUploadFileSize = 8;
				maxUploadFileSize = 0;
				int maxSize = maxUploadFileSize * 1024 * 1024;
				String path = env.getRealUploadPath();
				MultipartRequest multi = new MultipartRequest(httprequest, path, maxSize, "GBK",
						new DateBasedRenamePolicy());
				servletRequest.setAttribute("MultipartRequest", multi);
			} catch (Exception e) {
				RequestDispatcher rd = httprequest.getRequestDispatcher(HintTag.FORWARD_PAGE);
				String msg = e.getMessage();
				httprequest.setAttribute(HintTag.ATTRNAME_INFO, msg);
				rd.forward(servletRequest, servletResponse);
				return;
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}
}
